import func from "./func"

export default {
  accessToken: process.env.VUE_APP_TOKEN_KEY,
  refreshToken: process.env.VUE_APP_TOKEN_REFRESH_KEY,
  uuidToken: process.env.VUE_APP_UUID_KEY,
  userObj: {},
  getUUID() {
    // if (has()) {
    //   let tmpArray = get().split(".")
    //   if (tmpArray.length == 3) {
    //     let userJsonString = decodeURIComponent(escape(window.atob(tmpArray[1])))
    //     userObj = JSON.parse(userJsonString)

    //     return userObj["access_uuid"]
    //   }
    // }

    let uuid = sessionStorage.getItem(this.uuidToken)
    if (!uuid) {
      uuid = func.uuid()
      sessionStorage.setItem(this.uuidToken, uuid)
    }
    return uuid
  },
  setUUID(uuid) {
    sessionStorage.setItem(this.uuidToken, uuid)
  },
  deleteUUID() {
    sessionStorage.removeItem(this.uuidToken)
  },
  getObjByJWT(JWT) {
    let tmpArray = JWT.split(".")
    let returnObj = {}
    if (tmpArray.length == 3) {
      try {
        let userJsonString = decodeURIComponent(
          escape(window.atob(tmpArray[1]))
        )
        returnObj = JSON.parse(userJsonString)
      } catch (e) {
        console.log(e)
        returnObj = {}
      }
    }
    return returnObj
  },
  set(token, refresh, keep) {
    this.clear()
    sessionStorage.setItem(this.accessToken, token)
    sessionStorage.setItem(this.refreshToken, refresh)
    if (keep == true) localStorage.setItem(this.refreshToken, refresh)
  },
  get() {
    return sessionStorage.getItem(this.accessToken)
  },
  getRefreshToken() {
    let token = sessionStorage.getItem(this.refreshToken)
    //
    if (!token) {
      token = localStorage.getItem(this.refreshToken)
    }
    return token
  },
  has() {
    if (!this.get()) {
      return false
    }
    return true
  },
  clear() {
    sessionStorage.clear()
    this.getUUID()
  },
  localClear() {
    localStorage.clear()
  },
}
